Categories
JavaScript

Custom Validation with Joi — Annotations and Failover Values

Spread the love

Joi is a library that lets us validate an object’s structure with ease.

In this article, we’ll look at how to validate objects with Joi.

any

any creates a schema that matches any data type:

const any = Joi.any();
await any.validateAsync('a');

failover

We can set a failover value if schema validation fails with failover .

forbidden

forbidden lets us mark a key as forbidden:

const schema = {
  a: Joi.any().forbidden()
};

Now validation fails if a is in our object.

id

The id method lets us set the schema ID for getting the schema.

invalid

invalid lets us mark invalid values:

const schema = {
  a: Joi.any().invalid("a"),
  b: Joi.any().invalid("b", "B")
};

label

label lets us override the key name in error messages:

const schema = {
  name: Joi.string().label("Name")
};

meta

meta lets us add metadata to a key:

const schema = Joi.any().meta({ index: true });

note

note adds notes to as individual arguments to annotate it:

const schema = Joi.any().note('this is special', 'this is important');

optional

optional marks a key as optional:

const schema = Joi.any().optional();

prefs

prefs lets us sets the validation options.

raw

raw outputs the original untouched value instead of the casted value.

So if we have:

const rawTimestampSchema = Joi.date().timestamp().raw();
rawTimestampSchema.validate('12376834097810');

We validate the string instead of casting it to a Date object.

required

required make a key as required:

const schema = Joi.any().required();

ruleset

ruleset lets us apply multiple rule options:

const schema = Joi.number().ruleset.min(1).max(20).rule({ message: 'Number must be between 1 and 20' });

shared

shared registers a schema to be used by descendants of the schema in linked references.

If we have:

const schema = Joi.object({
  a: [Joi.string(), Joi.link("#x")],
  b: Joi.link("#type.a")
})
  .shared(Joi.number().id("x"))
  .id("type");

Then b and x is validated with the rules from a

strip

strip marks a key to be removed from an object or array after validation to sanitize output:

const schema = Joi.object({
  username: Joi.string(),
  password: Joi.string().strip()
});

password will be removed from the output if we validate against this schema.

tag

The tag method annotated the key with tags:

const schema = Joi.any().tag('foo', 'bar');

tailor

tailor returns a schema which is created by alter :

const schema = Joi.object({
  key: Joi.string().alter({
    get: (schema) => schema.required(),
    post: (schema) => schema.forbidden()
  })
});

const getSchema = schema.tailor("get");

getSchema would be the value of the get property.

unit

unit annotates the unit:

const schema = Joi.number().unit('milliseconds');

valid

valid marks the valid values:

const schema = {
  a: Joi.any().valid("a")
};

'a' is the valid value of a .

validate

validate validates data with a schema:

const schema = Joi.object({
  a: Joi.number()
});

const value = {
  a: "123"
};

const result = schema.validate(value);

result would be true because value.a is a number.

validateAsync

validateAsync does the validation asynchronously.

It returns a promise which resolves to the validation result.

warning

warning sets the warning:

const schema = Joi.any()
    .warning('custom.x', { w: 'world' })
    .message({ 'custom.x': 'hello {#w}!' });

const { value, error, warning } = schema.validate('anything');

#w has the value of w in the object we pass in.

Conclusion

We can customize our validation with warnings, references, and other annotations.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *